#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   curd.py
@Time    :   2021/02/08 00:12:14
@Author  :   superjin
@Version :   1.0
'''

from hashlib import new
from os import name
from typing import Any, Optional, List
from sqlalchemy import func,and_
from sqlalchemy.orm import Session
from models.xclass import XClass
from models.user import User


class CRUDClass:
    def add_class(self,db,newXClass):
        course = XClass(newXClass.name,newXClass.department,newXClass.grade,newXClass.major)
        db.add(course)
        db.commit()
        db.refresh(course)
        return course
    def get_class(self,db,class_id):
        res = db.query(XClass).filter_by(
            class_id=class_id).first()
        return res
    def modify_class():
        pass
    def list_class(self, db: Session, page:int, pageSize:int):
        data = db.query(XClass).offset((page-1)*pageSize).limit(pageSize).all()
        total = db.query(func.count(XClass.class_id)).scalar()
        return data,total
    
    def list_class_student(self, db: Session, page:int, pageSize:int,class_id:int = 1):
        data = db.query(User).filter_by(class_id=class_id).offset((page-1)*pageSize).limit(pageSize).all()
        total = db.query(func.count(User.class_id)).scalar()
        return data,total
    def add_student(self,db,user_id,class_id):
        res = db.query(User).filter_by(user_id=user_id).update(
                    {"class_id":class_id})
        db.commit()
        return res


xclass = CRUDClass()
